package com.yc.yn.controller;

import com.yc.yn.model.TSUser;
import com.yc.yn.model.resultVo.AjaxJson;
import com.yc.yn.model.resultVo.UsersVO;
import com.yc.yn.service.impl.UserServiceImpl;
import com.yc.yn.support.utils.PasswordUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserServiceImpl userService;

	@RequestMapping(value = "/registOrLogin", method = RequestMethod.POST)
	public AjaxJson registOrLogin(@RequestBody TSUser user) {
		// 0. 判断用户名和密码不能为空
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return AjaxJson.errorMsg("用户名或密码不能为空...");
		}
		// 1. 判断用户名是否存在，如果存在就登录，如果不存在则注册
		TSUser userResult = userService.queryUsernameIsExist(user.getUsername());
		if (userResult != null) {
			// 1.1 登录
			String saltPassWord = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), PasswordUtil.getStaticSalt());
			if (!saltPassWord.equals(userResult.getPassword())) {
				return AjaxJson.errorMsg("用户名或密码不正确...");
			}
		} else {
			// 1.2 注册
			user.setNickname(user.getUsername());
			user.setFaceImage("");
			user.setFaceImageBig("");
			user.setPassword(PasswordUtil.encrypt(user.getUsername(), user.getPassword(), PasswordUtil.getStaticSalt()));
			userResult = userService.saveUser(user);
		}
		UsersVO userVO = new UsersVO();
		BeanUtils.copyProperties(userResult, userVO);
		return AjaxJson.ok(userVO);
	}


}
